// pages/insuranceAppo/insuranceAppo.js
import config from "../../config.js";
var util = require('../../utils/util.js');
const openIdUrl = config;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uploadImg: "https://app.longchg.com/gudongcar/images/upload.jpg",
    //城市列表
    carList: [],
    carIndex: 0,
    typeList: [],
    typeIndex: 0,
    companyList: [],
    companyIndex: 0,
    backAddress: "",
    getAddress: "",
    wxAddress: "",
    orderType: 0,
    chuType: 0,
    latitude: 0,
    longitude: 0,
    getLatitude: '',
    getLongitude: '',
    backLatitude: '',
    backLongitude: '',
    wxAddress: '',
    wxLatitude: 0,
    wxLongitude: 0,
    defaultKeeper: {
      name: '',
      header: '',
      houseKeeperId: null
    },
    date: util.getDate(),
    mindate: util.getDate(),
    dateBack: util.getDate(),
    time: util.getMinute(),
    time: util.getMinute(),
    mintime: util.getMinute(),
    timeBack: util.getMinute(),
    // 是否上牌
    hasNo: true,
    tel: "",
    buList: [],
    buIndex: 0,
    isNeed: 0,
    orderId: -1,
    order: null,
    isShowPickLoaction: true,
    isShowReturnLoaction: true,
    isShowPickTime: true,
    undetermined: false,
    unwdetermined: false,
    //行驶证
    licenseFr: "https://app.longchg.com/gudongcar/images/licenseA.png",
    licenseBa: "https://app.longchg.com/gudongcar/images/licenseB.png",
    //身份证
    idenCardA: "https://app.longchg.com/gudongcar/images/idenCardA.png",
    idenCardB: "https://app.longchg.com/gudongcar/images/idenCardB.png",
    isUploadFr: false,
    isUploadBa: false,
    isUploadIDFr: false,
    isUploadIDBa: false,
    isUploadFirst: true,
    isUploadBaFirst: true,
    isUploadIDFirst: true,
    isUploadBaIDFirst: true,
    isFirst: true


  },
  determinTap: function() {
    this.setData({
      undetermined: !this.data.undetermined,
      backAddress: ''
    })
  },
  wdeterminTap: function() {
    this.setData({
      unwdetermined: !this.data.unwdetermined,
      wxAddress: ''
    })
  },
  dateChange: function(e) {
    var time = util.getMinute();
    var date = e.detail.value;
    var currentDate = util.getDate();
    var mintime = this.data.mintime;



    if (date != currentDate) {
      mintime = "";
    } else {
      mintime = util.getMinute();
      this.setData({
        time: time
      })
    }


    this.setData({
      date: e.detail.value,
      mintime: mintime,
    })
  },
  chuChange: function(e) {
    this.setData({
      chuType: e.detail.value,
    })
  },
  isNeedChange: function(e) {
    this.setData({
      isNeed: e.detail.value,
    })
    console.log(this.data.isNeed);
  },

  buChange: function(e) {
    this.setData({
      buIndex: e.detail.value,
    })
  },

  timeChange: function(e) {
    this.setData({
      time: e.detail.value,
    })
  },


  getTypeList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.stepServiceTypeList,
      data: {
        start: 0,
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          console.log(res.data.data);
          for (var i = 0; i < res.data.data.length; i++) {
            var item = res.data.data[i];
            if (item.name == '自取自送') {
              res.data.data.splice(i, 1);
            }
          }
          that.setData({
            typeList: res.data.data
          })

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },
  getComList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.insuranceComList,
      data: {
        start: 0,
        isNor: 1
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          console.log(res.data.data);
          that.setData({
            companyList: res.data.data
          })

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },
  getBuList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.stepCarInfo,
      data: {
        start: 0,
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          console.log(res.data.data);
          that.setData({
            buList: res.data.data
          })

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },
  submit: function() {

    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    var user = wx.getStorageSync("user");
    var carId = that.data.carList[that.data.carIndex].cid;
    var serviceType = that.data.typeList[that.data.typeIndex].typeId;
    var comId = that.data.companyList[that.data.companyIndex].insuranceId;
    var orderFrom = 1;
    if (serviceType != 3 && that.data.getAddress == "") {
      wx.showToast({
        title: "请选择接车地点",
        icon: 'none',
        mask: true,
        duration: 2000
      })
      return false;
    }
    if (that.data.undetermined == false && serviceType != 2) {
      if (that.data.backAddress == "") {
        wx.showToast({
          title: "请选择还车地点",
          icon: 'none',
          mask: true,
          duration: 2000
        })
        return false;
      }
    }
    if (that.data.tel == "") {
      wx.showToast({
        title: "请输入联系电话",
        icon: 'none',
        mask: true,
        duration: 2000
      })
      return false;
    }

    var isUploadFr = this.data.isUploadFr,
      isUploadBa = this.data.isUploadBa,
      isUploadIDFr = this.data.isUploadIDFr,
      isUploadIDBa = this.data.isUploadIDBa,
      licenseFr = this.data.licenseFr,
      licenseBa = this.data.licenseBa,
      idenCardA = this.data.idenCardA,
      idenCardB = this.data.idenCardB;

    if (that.data.isNeed == 1) {
      if (!isUploadFr) {
        wx.showToast({
          title: '请选择行驶证正面',
          icon: 'none',
        })
        return;
      } else if (!isUploadBa) {
        wx.showToast({
          title: '请选择行驶证反面',
          icon: 'none',
        })
        return;
      }


      wx.setStorageSync("licenseFr", licenseFr);
      wx.setStorageSync("licenseBa", licenseBa);
      wx.setStorageSync("idenCardA", idenCardA);
      wx.setStorageSync("idenCardB", idenCardB);
    }


    var time = that.data.date + " " + that.data.time;
    var timeBack = that.data.dateBack + " " + that.data.timeBack;

    wx.setStorageSync("comId", comId);
    wx.setStorageSync("timePick", time);
    wx.setStorageSync("orderFrom", orderFrom);
    wx.setStorageSync("timeReturn", timeBack);
    wx.setStorageSync("serviceType", serviceType);
    wx.setStorageSync("backAddress", that.data.backAddress);
    wx.setStorageSync("getAddress", that.data.getAddress);
    wx.setStorageSync("getLatitude", that.data.getLatitude);
    wx.setStorageSync("getLongitude", that.data.getLongitude);
    wx.setStorageSync("backLatitude", that.data.backLatitude);
    wx.setStorageSync("backLongitude", that.data.backLongitude);
    wx.setStorageSync("chuType", that.data.chuType);
    wx.setStorageSync("orderFrom", 1);
    wx.setStorageSync("undetermined", that.data.undetermined);
    wx.setStorageSync("unwdetermined", that.data.unwdetermined);
    wx.setStorageSync("isNeed", that.data.isNeed);
    wx.setStorageSync("stepcar", that.data.buList[that.data.buIndex].carId);
    wx.setStorageSync("stepcar", that.data.buList[that.data.buIndex].carId);
    // wx.navigateTo({
    //   url: '../repairDetail/repairSubmitDetail',
    // })
    if (that.data.orderId != -1) {
      wx.setStorageSync("reqairListAgain", this.data.order.service.repairServiceItems);
      wx.navigateTo({
        url: '../repairDetail/repairSubmitDetail?isAgain=1&keeperId=' + that.data.defaultKeeper.houseKeeperId,
      })
    } else {
      wx.navigateTo({
        url: '../repairDetail/repairSubmitDetail?keeperId=' + that.data.defaultKeeper.houseKeeperId,
      })
    }
  },
  getCarList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.myCarsList,
      data: {
        // id: 1,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          console.log(res.data.data);
          that.setData({
            carList: res.data.data
          })

          if (that.data.carList != null && that.data.carList.length != 0 && that.data.isUploadBaFirst == true && that.data.isUploadFirst == true) {
            var car = that.data.carList[that.data.carIndex];
            wx.setStorageSync("carId", car.cid);
            //设置默认车辆图片信息
            that.setData({
              isUploadFr: true,
              isUploadBa: true,
              isUploadBaFirst: false,
              isUploadFirst: false,
              licenseFr: car.wdxlicensePic,
              licenseBa: car.wdxlicensePicB
            })
          }

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },

  carChange: function(e) {
    this.setData({
      carIndex: e.detail.value,
    })
    var car = this.data.carList[this.data.carIndex];
    //设置默认车辆图片信息
    this.setData({
      isUploadBaFirst: false,
      isUploadFirst: false,
      licenseFr: car.wdxlicensePic,
      licenseBa: car.wdxlicensePicB
    })
  },

  typeChange: function(e) {
    this.setData({
      typeIndex: e.detail.value,
    })

    var item = this.data.typeList[this.data.typeIndex];
    switch (item.typeId) {
      case 2:
        this.setData({
          isShowPickLoaction: true,
          isShowReturnLoaction: false,
          isShowPickTime: true,
        })
        break;
      case 3:
        this.setData({
          isShowPickLoaction: false,
          isShowReturnLoaction: true,
          isShowPickTime: false,
        })
        break;

      default:
        this.setData({
          isShowPickLoaction: true,
          isShowReturnLoaction: true,
          isShowPickTime: true,
        })
        break;
    }
  },
  companyChange: function(e) {
    this.setData({
      companyIndex: e.detail.value,
    })
  },

  servChange: function(e) {
    this.setData({
      servIndex: e.detail.value,
    })
  },

  telChange: function(e) {
    this.setData({
      tel: e.detail.value,
    })
  },
  getChange: function(e) {
    this.setData({
      getAddress: e.detail.value,
    })
  },

  selectNo: function() {
    let flag = this.data.hasNo;
    if (flag) {
      this.setData({
        hasNo: false
      })
    } else {
      this.setData({
        hasNo: true
      })
    }
  },



  toAppoPage: function() {
    wx.navigateTo({
      url: "../insurPlan/insurPlan",
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var that = this;
    //判断是否是再次下单或者更改订单类型
    var orderId = options.orderId;
    this.setData({
      date: util.getDate(),
      dateBack: util.getDate(),
      time: util.getMinute(),
      timeBack: util.getMinute(),
      tel: wx.getStorageSync("user").tel
    })
    if (orderId == null) {

      if (wx.getStorageSync('user') != null) {
        that.setData({
          'defaultKeeper.name': wx.getStorageSync("user").housekeeper.name,
          'defaultKeeper.header': wx.getStorageSync("user").housekeeper.image,
          'defaultKeeper.houseKeeperId': wx.getStorageSync("user").housekeeper.keeperId
        })
      }
    } else {
      that.setData({
        orderId: orderId
      })

      //获取订单详情
      that.orderDetail();

    }
    if (wx.getStorageSync('user') != null) {
      that.setData({
        'defaultKeeper.name': wx.getStorageSync("user").housekeeper.name,
        'defaultKeeper.header': wx.getStorageSync("user").housekeeper.image,
        'defaultKeeper.houseKeeperId': wx.getStorageSync("user").housekeeper.keeperId
      })
    }

    this.getTypeList();

    var that = this;
    setTimeout(function() {
      that.getBuList();
    }, 500);
    setTimeout(function() {
      that.getCarList();
    }, 300);
    setTimeout(function() {
      that.getComList();
    }, 100);

    var that = this;
    util.checkLocationIsOff(this)
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      }
    })

  },

  orderDetail() {
    var that = this;
    //获取订单详情
    wx.request({
      url: openIdUrl.orderDetailUrl,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        id: this.data.orderId
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          that.setData({
            order: res.data.data
          })
          that.setOrderData();
        } else {
          wx.showToast({
            title: '订单获取失败！',
            icon: 'none',
            duration: 1500
          })
          return false;
        }
      }

    })
  },
  setOrderData() {
    var that = this;
    //订单信息
    var order = that.data.order.order;
    var service = that.data.order.service;
    var data1 = new Date(service.boardingTime);
    var data2 = new Date(service.connectionTime);
    that.setData({
      dateBack: data1.getFullYear() + "-" + (data1.getMonth() + 1) + "-" + data1.getDate(),
      date: data2.getFullYear() + "-" + (data2.getMonth() + 1) + "-" + data2.getDate(),
      latitude: service.locationByPickupLocId.locLatitude,
      longitude: service.locationByReturnLocId1.locLongitude,
      getLatitude: service.locationByPickupLocId.locLatitude,
      getLongitude: service.locationByReturnLocId1.locLongitude,
      backLatitude: service.locationByPickupLocId.locLatitude,
      backLongitude: service.locationByReturnLocId1.locLongitude,
      getAddress: service.locationByPickupLocId.name,
      backAddress: service.locationByReturnLocId1.name,
      companyIndex: service.insuranceCom.insuranceId - 1,
      tel: service.tel,
      // isPeccancy: service.isPeccancy,
      // isRefit: service.isRefit,
      typeIndex: service.stepCarServiceType.typeId - 1,
      time: (data2.getHours() < 10 ? ("0" + data2.getHours()) : data2.getHours()) + ":" + (data2.getMinutes() < 10 ? ("0" + data2.getMinutes()) : data2.getMinutes()),
      timeBack: (data1.getHours() < 10 ? ("0" + data1.getHours()) : data1.getHours()) + ":" + (data1.getMinutes() < 10 ? ("0" + data1.getMinutes()) : data1.getMinutes())
    })

    var houseKeeper = order.housekeeper;
    if (houseKeeper) {
      this.setData({
        "defaultKeeper.name": houseKeeper.name,
        "defaultKeeper.houseKeeperId": houseKeeper.keeperId,
        "defaultKeeper.header": houseKeeper.image,
      })
    }

    that.getCarList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    if (!that.data.isFirst) {
      var houseKeeper = wx.getStorageSync("houseKeeper");
      if (houseKeeper) {
        this.setData({
          "defaultKeeper.name": houseKeeper.name,
          "defaultKeeper.houseKeeperId": houseKeeper.keeperId,
          "defaultKeeper.header": houseKeeper.image,
        })
      }
    }
    var user = wx.getStorageSync('user');
    if (user.licenseA != null && user.licenseB != null && that.data.isUploadIDFirst == true && that.data.isUploadBaIDFirst == true) {
      //设置默认车辆图片信息
      console.log(user);
      that.setData({
        isUploadIDFirst: false,
        isUploadBaIDFirst: false,
        idenCardA: user.licenseA,
        idenCardB: user.licenseB,
        isUploadIDFr: true,
        isUploadIDBa: true,
        isUploadFr: true,
        isUploadBa: true,
      })
    }


    that.setData({
      isFirst: false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    wx.setStorageSync("houseKeeper", null);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.setStorageSync("houseKeeper", null);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  orderAction() {
    wx.showModal({
      title: "恭喜您",
      content: "预约成功，车管家将会在10分钟内通过电话与您沟通详情 ，请保持电话畅通！谢谢！",
      showCancel: false,
      confirmColor: "#137AF0",
      success: function() {
        wx.switchTab({
          url: "../order/order",
        })
      }
    })
  },
  chooseMap: function() {
    var that = this;
    util.checkLocationIsOff(this)
    wx.chooseLocation({
      success: function(res) {
        console.log(res);
        that.setData({
          getAddress: res.address,
          getLatitude: res.latitude,
          getLongitude: res.longitude,
        })
      },
    })
  },
  chooseMap2: function() {
    var that = this;
    util.checkLocationIsOff(this)
    wx.chooseLocation({
      success: function(res) {
        console.log(res);
        that.setData({
          backAddress: res.address,
          backLatitude: res.latitude,
          backLongitude: res.longitude,
        })
      }
    })
  },
  chooseMap3: function() {
    var that = this;
    util.checkLocationIsOff(this)
    wx.chooseLocation({
      success: function(res) {
        console.log(res);
        that.setData({
          wxAddress: res.address,
          wxLatitude: res.latitude,
          wxLongitude: res.longitude,
        })
      }
    })
  },
  loadMap() {
    wx.navigateTo({
      url: '../map/map',
    })
  },
  changeKeeper: function() {
    var instance = this;
    wx.navigateTo({
      url: '../managerList/managerList',
    })
  },
  //行驶证
  uploadFr: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          licenseFr: tempFilePaths,
          isUploadFr: true,
          isUploadFirst: false
        })

        console.log(that.data.licenseFr);


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.licenseFr[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function(res) {
            wx.hideLoading();
            res = JSON.parse(res.data);
            console.log(res);
            if (res.status == 200) {
              that.setData({
                isUploadFr: true,
              })
              that.data.licenseFr = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },

  uploadBa: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          licenseBa: tempFilePaths,
          isUploadBa: true,
          isUploadBaFirst: false
        })


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.licenseBa[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function(res) {
            wx.hideLoading();
            console.log(res);
            res = JSON.parse(res.data);
            if (res.status == 200) {
              that.setData({
                isUploadBa: true,
              })
              that.data.licenseBa = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },
  //身份证正面
  uploadFrID: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          idenCardA: tempFilePaths,
          isUploadIDFr: true,
          isUploadIDFirst: false
        })


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.idenCardA[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function(res) {
            wx.hideLoading();
            res = JSON.parse(res.data);
            console.log(res);
            if (res.status == 200) {
              that.setData({
                isUploadIDFr: true,
              })
              that.data.idenCardA = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },

  uploadBaID: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          idenCardB: tempFilePaths,
          isUploadIDBa: true,
          isUploadBaIDFirst: false
        })


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.idenCardB[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function(res) {
            wx.hideLoading();
            console.log(res);
            res = JSON.parse(res.data);
            if (res.status == 200) {
              that.setData({
                isUploadIDBa: true,
              })
              that.data.idenCardB = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },
})